<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :btn-list="fullInfo.btnList"
      @returnBack="$emit('returnModify')"
    >
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
            @handleEvent="changeHandle"
          >
            <template v-slot:form-supplierName>
              <el-input
                v-model="formInfo.data.supplierName"
                class="not-br not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择供应商"
              >
                <template #append>
                  <el-icon @click="openSupplierWindow"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
          </page-form>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')"></Tooltip>
        </div>
        <div class="model-panel-body">
          <div class="filter-wrapper">
            <!-- 条件栏 -->
            <page-filter
              v-model:query="filterInfo.query"
              :filter-list="filterInfo.list"
            >
              <template v-slot:filter-addProduct>
                <el-button @click="addProduct">选择配送单产品</el-button>
              </template>
              <template v-slot:filter-removeProduct>
                <el-button
                  :disabled="!canRemoveProduct"
                  @click="removeProduct()"
                  >删除配送单产品</el-button
                >
              </template>
            </page-filter>
          </div>
          <div class="flex_full_item">
            <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
              <!-- 表格 -->
              <page-table
                ref="table"
                class="table-scroll-hidden"
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :tab-index="false"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :row-class-name="tableRowClassName"
                :cell-class-name="tableCellClassName"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-receivingQty="scope">
                  <el-form-item class="margin-bottom">
                    <div class="page-table-input-number-wrapper">
                      <div class="page-table-input-number-left">
                        <div class="page-table-input-number-item">
                          <el-form-item
                            :prop="`data.${scope.$index}.receivingQty`"
                            :rules="
                              scope.$index >= 0
                                ? [
                                    {
                                      validator: $validate.positiveAndZero,
                                      trigger: 'blur',
                                    },
                                  ]
                                : []
                            "
                          >
                            <el-input-number
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.receivingQty"
                              clearable
                              controls-position="right"
                              @change="
                                changeLarge(
                                  $event,
                                  `data.${scope.$index}.receivingQty`
                                )
                              "
                              :min="0"
                              :max="largeMax(scope.row)"
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.preNetworkUnit }}
                          </div>
                        </div>
                      </div>
                    </div>
                  </el-form-item>
                </template>
                <template v-slot:col-deliverQty="scope">
                  <span v-if="scope.row.deliverQty">
                    {{ scope.row.deliverQty + scope.row.preNetworkUnit }}
                  </span>
                  <span v-else>-</span>
                </template>
                <template v-slot:col-preNetworkPrice="scope">
                  <span v-if="scope.row.preNetworkPrice">
                    {{
                      scope.row.preNetworkPrice +
                      '元/' +
                      scope.row.preNetworkUnit
                    }}
                  </span>
                  <span v-else>-</span>
                </template>
                <template v-slot:col-preNetworkUnit="scope">
                  <span v-if="scope.row.preNetworkUnit">
                    {{ scope.row.preNetworkUnit }}
                  </span>
                  <span v-else>-</span>
                </template>
                <template v-slot:col-remark="scope">
                  <el-form-item class="margin-bottom">
                    <div class="page-table-input-number-wrapper">
                      <div class="page-table-input-number-left">
                        <div class="page-table-input-number-item">
                          <el-form-item :prop="`data.${scope.$index}.remark`">
                            <el-input
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.remark"
                              clearable
                            />
                          </el-form-item>
                        </div>
                      </div>
                    </div>
                  </el-form-item>
                </template>
              </page-table>
            </el-form>
          </div>

          <!-- 选择产品 -->
          <addProductSelect
            v-if="productInfo.visible"
            v-model:show-dialog="productInfo.visible"
            :query="productInfo.query.queryMap"
            :query-params="productInfo.query.queryParams"
            :api="productInfo.api"
            title="选择配送单产品"
            :notDefaultProductSupplier="false"
            :table-key="productInfo.tableKey"
            @callback="selectProductCallback"
          />
          <select-supplier
            v-if="selectSupplierInfo.visible"
            v-model:show-dialog="selectSupplierInfo.visible"
            :check-box="false"
            :highlight-row="true"
            :query="selectSupplierInfo.query"
            :api="selectSupplierInfo.api"
            @callback="selectSupplierCallback"
          />
        </div>
      </div>
    </NewFullScreen>
  </div>
</template>

<script setup name="receiptModify">
import {
  selectDeliverOrder,
  saveProvinceReceivingOrder,
  saveProvinceReceivingOrderAndSave,
  detailsProvinceReceivingOrder,
  modifyProvinceReceivingOrder,
} from '@/api/province'
import { getCustomizeSetting } from '@/api/customize'
import addProductSelect from './addProductSelect'
import _, { isEqualWith } from 'lodash'
import SelectSupplier from '@/views/province/components/selectSupplier'
import { getMappingTripartiteSupplierPage } from '@/api/tripartite'
const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps(['visible', 'title', 'orderId'])
const formRefs = ref([])

const selectSupplierInfo = ref({
  visible: false,
  api: getMappingTripartiteSupplierPage,
  query: {
    sort: 'create_time desc',
    tsSystemCode:
      proxy.$store.state.permission.systemConfig
        .connect_purchase_platform_system,
    reserved1: '', //试剂or1耗材
  },
})
const formInfo = ref({
  ref: null,
  data: {
    networkProductType: 1,
    supplierName: '',
    supplierId: '',
  },
  rules: {
    supplierName: [
      { required: true, message: '请选择供应商', target: 'change' },
    ],
  },
  fieldList: [
    {
      label: '挂网产品类型',
      value: 'networkProductType',
      type: 'select-model',
      code: 'network_product_type',
      checkDefault: true,
      disabled: props.orderId ? true : false,
    },
    {
      label: '供应商',
      value: 'supplierName',
      type: 'slot',
      disabled: props.orderId ? true : false,
    },
  ],
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {},
  },
  list: [
    { type: 'slot', label: '选择配送单产品', value: 'addProduct' },
    { type: 'slot', label: '删除配送单产品', value: 'removeProduct' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '150',
    btList: [
      {
        label: '删除配送单产品',
        event: removeProduct,
        show: true,
      },
    ],
  },
})

const fullInfo = ref({
  btnList: [{ label: '保存并提交', event: saveAndSubmit, show: !props.orderId && proxy.$permission("provinceReceipt:saveAndSubmit") },{ label: '保存', event: save, show: true }],
})
//选择产品相关
const productInfo = ref({
  visible: false,
  api: selectDeliverOrder,
  tableKey:
    'provinceReceivingOrderSelectDeliverOrderPage-com.slip.spd.entity.vo.provincePlatform.ProvinceDeliveryOrderVO',
  query: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: null,
      },
      supplierId: {
        queryType: 'IN',
        value: null,
      },
      type:{
        asTbName: 'core_product_new',
        columnName: 'type',
        queryCategory: 'AND',
        queryResource: 0,
        queryType: 'EQUALS',
        value: 0,
      }
    },
    queryParams: { receivingFlag: true },
  },
  searchList: [],
})

const selectRow = ref('')

//用于显示取值
const systemConfig = ref(proxy.$store.state.permission.systemConfig)

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})

const canRemoveProduct = computed(() => {
  return tableInfo.value.selections.length
})

watch(
  () => tableInfo.value.data,
  () => {
    tableInfo.value.data.forEach((row) => {
      row.sumAmount = proxy.$fn.accMul(
        row.receivingQty || 0,
        row.preNetworkPrice || row.price || 0
      )
    })
  },
  {
    deep: true,
  }
)

setData()
function setData() {
  let obj = {
    receivingQty: {
      label: '收货数量',
      value: 'receivingQty',
      type: 'slot',
      minWidth: '250px',
      hidden: true,
    },
    deliverQty: {
      label: '配送数量',
      value: 'deliverQty',
      type: 'slot',
      minWidth: '250px',
      hidden: true,
    },
    preNetworkPrice: {
      label: '省采单价',
      value: 'preNetworkPrice',
      type: 'slot',
      minWidth: '250px',
      hidden: true,
    },
    preNetworkUnit: {
      label: '省采单位',
      value: 'preNetworkUnit',
      type: 'slot',
      minWidth: '250px',
      hidden: true,
    },
    remark: {
      label: '收货备注',
      value: 'remark',
      type: 'slot',
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
}
function changeHandle(e, val) {
  formInfo.value.data.supplierId = ''
  formInfo.value.data.supplierName = ''
  tableInfo.value.data = []
}
function changeLarge(e, str) {
  proxy.$refs.tableForm.clearValidate(str)
}
function largeMax(row) {
  return row.deliverQty
}
function smallMax(row) {
  if (
    systemConfig.value.use_convert_count_restrict == 1 &&
    formInfo.value.data.useId &&
    (row.maxConvertCount || row.maxConvertCount === 0)
  ) {
    return parseInt((row.maxConvertCount || 0) % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
// 触发事件
function handleEvent(event, data) {
  const _tableInfo = tableInfo.value
  switch (event) {
    case 'tableCheck':
      _tableInfo.selections = [...data]
      break
  }
}
function openSupplierWindow() {
  if (props.orderId) {
    return
  }
  //选择供应商
  selectSupplierInfo.value.query.reserved1 =
    formInfo.value.data.networkProductType
  selectSupplierInfo.value.visible = true
}
function selectSupplierCallback(data) {
  //选择供应商发回
  if (formInfo.value.data.supplierId !== data.spdOrgId) {
    formInfo.value.data['supplierId'] = data.spdOrgId
    formInfo.value.data['supplierName'] = data.name

    productInfo.value.query.queryMap.supplierId.value = data.spdOrgId
    tableInfo.value.data = []
  }
  console.log(productInfo.value.query.queryMap)
}

//添加产品按钮
function addProduct() {
  if (!formInfo.value.data.supplierName) {
    proxy.$message({
      duration: 3000,
      type: 'warning',
      showClose: true,
      message: '请选择供应商',
    })
    return
  }
  const _tableInfo = tableInfo.value
  let idNotIn = _tableInfo.data.map(function (item) {
    return item.deliverOrderId
  })
  productInfo.value.query.queryMap.id.value = idNotIn.toString()
  if (props.orderId) {
    productInfo.value.query.queryParams.existReceivingOrderId = props.orderId
  }
  productInfo.value.query.queryMap.networkProductType = {
    queryType: 'IN',
    value: formInfo.value.data.networkProductType,
  }
    // 药品
    productInfo.value.query.queryMap.type = {
        asTbName: 'core_product_new',
        columnName: 'type',
        queryCategory: 'AND',
        queryResource: 0,
        queryType: 'EQUALS',
        value: formInfo.value.data.networkProductType == 3 ? 4 : 0,
      }
  
  console.log(productInfo.value.query.queryMap)
  productInfo.value.visible = true
}

function selectProductCallback(rows) {
  if (rows) {
    rows.map((item) => {
      item.receivingQty = item.warehouseCount
      item.deliverQty = item.distributeCount
      item.preNetworkUnit = item.networkUnit
      item.preNetworkPrice = item.price
      item.deliverOrderId = item.id
      item.provinceDeliverOrderDetailId = item.provinceDistributeId
      item.provincePurchOrderDetailId = item.provinceOrderDetailId
      item.remark = ''
    })
    tableInfo.value.data = rows.concat(tableInfo.value.data)
  }
}

//删除产品
function removeProduct(item) {
  if (item) {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.data = tableInfo.value.data.filter(
          (obj) => obj.id !== item.id
        )
      })
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.selectionsCopy = proxy.$fn.deepClone(
          tableInfo.value.selections
        )
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
      })
  }
}
function saveAndSubmit() {
  save(true)
}
function save(isSaveAndSubmit) {
  const _tableInfo = tableInfo.value
  proxy.$fn.checkForm(formRefs.value).then(() => {
    if (!_tableInfo.data.length) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '产品不能为空',
      })
      return
    }
    let newDetails = _tableInfo.data.filter((item) => item.receivingQty > 0)
    if (newDetails.length < _tableInfo.data.length) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '收货数量要大于0',
      })
      return
    } else {
      checkSave(isSaveAndSubmit)
    }
  })
}
function checkSave(isSaveAndSubmit) {
  const _formInfo = formInfo.value
  const _tableInfo = tableInfo.value

  let params = {
    details: [],
  }
  _tableInfo.data.map((item) => {
    console.log(item.provinceDistributeId, item.provinceDeliverOrderDetailId)
    params.details.push({
      deliverOrderId: item.deliverOrderId,
      deliverQty: item.distributeCount || item.deliverQty,
      provinceDeliverOrderDetailId: item.provinceDistributeId
        ? item.provinceDistributeId + ''
        : item.provinceDeliverOrderDetailId + '',
      provincePurchOrderDetailId: item.provinceOrderDetailId
        ? item.provinceOrderDetailId + ''
        : item.provincePurchOrderDetailId + '',
      preNetworkPrice: item.price || item.preNetworkPrice,
      preNetworkUnit: item.networkUnit || item.preNetworkUnit,
      productId: item.productId,
      returnQty: item.returnQty || 0,
      receivingQty: item.receivingQty,
      remark: item.remark,
      sumAmount: (item.price || item.preNetworkPrice) * item.receivingQty,
    })
  })
  if (props.orderId) {
    params.id = props.orderId
    params.status = formInfo.value.data.status
    params.orderNo = formInfo.value.data.orderNo
  }
  params.networkProductType = formInfo.value.data.networkProductType
  params.supplierName = formInfo.value.data.supplierName
  params.supplierId = formInfo.value.data.supplierId
  let api = isSaveAndSubmit === true ? saveProvinceReceivingOrderAndSave : saveProvinceReceivingOrder
  api(params).then((resp) => {
    if (resp && resp.success) {
      emits('returnModify', false)
      showDialog.value = false
    }
  })
}
function getReceiptOrderById(orderId) {
  detailsProvinceReceivingOrder(orderId).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data
      productInfo.value.query.queryMap.supplierId.value = resp.data.supplierId
      getReceiptOrderDetails()
    }
  })
}
function getReceiptOrderDetails() {
  modifyProvinceReceivingOrder(filterInfo.value.query).then((resp) => {
    if (resp && resp.success) {
      tableInfo.value.data = resp.data
      tableInfo.value.data.forEach((item) => {
        item.isConsignBusiness = item.isConsignment
        item.isConsignBusinessValue = item.isConsignmentValue
        item.supplierId = formInfo.value.data.supplierId
        item.supplierName = formInfo.value.data.supplierName
      })
    }
  })
}

function tableRowClassName({ row = undefined }) {}
function tableCellClassName({ column, row }) {
  if (row.calcQty === 0 && column.property === 'qty') {
    return 'cell-color'
  }
  return ''
}
function getCustomize(update = undefined) {
  let _tableInfo = tableInfo.value
  let param = {
    tableKey:
      'provinceReceivingOrderModify-com.slip.spd.entity.vo.provincePlatform.ProvinceReceivingOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      _tableInfo.fieldList = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail
      )

      filterInfo.value.query.customizeUserVO = data
      filterInfo.value.query.queryMap.orderId.value = props.orderId
      if (update) {
        let arr = []
        for (let key in data.detail) {
          arr.push(data.detail[key])
        }
        let sortArr = []
        arr.forEach((item) => {
          if (item.sortControllerType === 1) {
            sortArr.push({
              prop: item.fieldName,
              order: 'ascending',
            })
          } else if (item.sortControllerType === 2) {
            sortArr.push({
              prop: item.fieldName,
              order: 'descending',
            })
          }
        })
        if (sortArr.length) {
          proxy.$refs.table.$refs.table.sort(sortArr[0].prop, sortArr[0].order)
        }
        return
      }
      if (props.orderId) {
        getReceiptOrderById(props.orderId)
      }
    }
  })
}
</script>

<style scoped lang="scss">
.model-panel-title {
  display: flex;
  align-items: center;
  .model-tips {
    display: flex;
    align-items: center;
    margin-left: 10px;
    color: #909399;
    .model-tips-nearly,
    .model-tips-expire {
      display: block;
      margin-left: 5px;
      width: 17px;
      height: 17px;
    }
    .model-tips-nearly {
      background: #fceacb;
    }
    .model-tips-expire {
      background: #f5e4e4;
    }
  }
}
:deep(.el-table) {
  .nearly-row {
    background: #fceacb;
  }
  .expire-row {
    background: #f5e4e4;
  }
  .cell-color {
    background: #f4aed9bd;
  }
}
</style>
